import { Word } from '../models/word';

class SpacedRepetitionService {
  private static instance: SpacedRepetitionService;

  // 间隔重复时间间隔（小时）
  private intervals = [0, 4, 8, 20, 60, 144, 336]; // 新学、1级到5级

  private constructor() {}

  static getInstance(): SpacedRepetitionService {
    if (!SpacedRepetitionService.instance) {
      SpacedRepetitionService.instance = new SpacedRepetitionService();
    }
    return SpacedRepetitionService.instance;
  }

  /**
   * 根据用户回答正确性更新单词的下次复习时间
   * @param word 单词对象
   * @param isCorrect 回答是否正确
   * @returns 更新后的单词对象
   */
  updateWordSchedule(word: Word, isCorrect: boolean): Word {
    const now = new Date();

    if (isCorrect) {
      // 回答正确，提升难度等级
      word.correctCount += 1;
      word.reviewCount += 1;

      // 如果是新单词，设置为1级
      if (word.difficulty === 0) {
        word.difficulty = 1;
      } else if (word.difficulty < 5) {
        // 最多提升到5级
        word.difficulty += 1;
      }
    } else {
      // 回答错误，重置难度等级
      word.reviewCount += 1;
      word.difficulty = Math.max(1, word.difficulty - 1);
    }

    // 设置下次复习时间
    const intervalHours = this.intervals[word.difficulty];
    const nextReviewDate = new Date(now.getTime() + intervalHours * 60 * 60 * 1000);
    word.nextReviewDate = nextReviewDate;
    word.lastReviewed = now;

    return word;
  }

  /**
   * 获取需要复习的单词列表
   * @param words 所有单词
   * @returns 需要复习的单词列表
   */
  getWordsToReview(words: Word[]): Word[] {
    const now = new Date();
    return words.filter(word => new Date(word.nextReviewDate) <= now);
  }

  /**
   * 获取新单词（从未学习过的单词）
   * @param words 所有单词
   * @param count 需要的数量
   * @returns 新单词列表
   */
  getNewWords(words: Word[], count: number): Word[] {
    return words
      .filter(word => word.reviewCount === 0)
      .sort(() => 0.5 - Math.random())
      .slice(0, count);
  }
}

export default SpacedRepetitionService.getInstance();
